#include <stdio.h>
#include <stdlib.h>
#include <libusb-1.0/libusb.h>

// #define VENDOR_ID 0x0e0f // 你的鼠标的供应商ID
// #define PRODUCT_ID 0x0003 // 你的鼠标的产品ID
// 有线鼠标
#define VENDOR_ID 0x093a // 你的鼠标的供应商ID
#define PRODUCT_ID 0x2510 // 你的鼠标的产品ID
#define ENDPOINT_IN 0x81 // 输入端点

// 无线鼠标
// #define VENDOR_ID 0x25a7 // 你的鼠标的供应商ID
// #define PRODUCT_ID 0xfa23 // 你的鼠标的产品ID
// #define ENDPOINT_IN 0x82 // 输入端点
// #define MAX_BUF_SIZE 8 // 最大缓冲区大小

#define DATA_BUFFER_SIZE 8

int main() {
    libusb_context *ctx = NULL;
    libusb_device **devs;
    libusb_device_handle *handle = NULL;
    ssize_t num_devices = 0;
    int transfer_size = DATA_BUFFER_SIZE;
    unsigned char data[DATA_BUFFER_SIZE];
    int transferred = 0;
    int ret;

    // Initialize libusb
    if (libusb_init(&ctx) != 0) {
        fprintf(stderr, "Error initializing libusb\n");
        return 1;
    }

    // Get the list of USB devices
    num_devices = libusb_get_device_list(ctx, &devs);
    if (num_devices < 0) {
        fprintf(stderr, "Error getting device list\n");
        libusb_exit(ctx);
        return 1;
    }

    // Find and open the USB mouse device
    for (ssize_t i = 0; i < num_devices; i++) {
        libusb_device *dev = devs[i];
        struct libusb_device_descriptor desc;
        if (libusb_get_device_descriptor(dev, &desc) == 0) {
            if (desc.idVendor == VENDOR_ID && desc.idProduct == PRODUCT_ID) {
                // Open the USB device
                if (libusb_open(dev, &handle) == 0) {
                    break;
                }
            }
        }
    }

    if (handle == NULL) {
        fprintf(stderr, "USB mouse not found\n");
        libusb_free_device_list(devs, 1);
        libusb_exit(ctx);
        return 1;
    }

    libusb_set_auto_detach_kernel_driver(handle, 1);
    // Claim the interface (you may need to change the interface number)
    ret = libusb_claim_interface(handle, 0);
    if (ret != 0) {
        fprintf(stderr, "Error claiming interface: %s\n", libusb_error_name(ret));
        libusb_close(handle);
        libusb_free_device_list(devs, 1);
        libusb_exit(ctx);
        return 1;
    }

    printf("Reading USB mouse data...\n");

    // Main loop to read mouse data
    while (1) {
        ret = libusb_interrupt_transfer(handle, ENDPOINT_IN, data, transfer_size, &transferred, 5000);
        if (ret == 0) {
            // Process and use the mouse data in the 'data' buffer here
            printf("Mouse data received: ");
            for (int i = 0; i < transferred; i++) {
                printf("%02X ", data[i]);
            }
            printf("\n");
        } else {
            fprintf(stderr, "Error reading data: %s\n", libusb_error_name(ret));
        }
    }

    // Release the interface and close the USB device
    libusb_release_interface(handle, 0);
    libusb_close(handle);

    // Free the device list and exit libusb
    libusb_free_device_list(devs, 1);
    libusb_exit(ctx);

    return 0;
}
